<template>
  <div class="game-container">
    <h1>Vue 3 贪吃蛇</h1>
    <div class="game-board" ref="gameBoard" tabindex="0" @keydown="handleKeyDown">
      <div 
        v-for="(row, y) in grid" 
        :key="'row'+y" 
        class="row"
      >
        <div 
          v-for="(cell, x) in row" 
          :key="`cell-${x}-${y}`"
          class="cell"
          :class="{
            'snake': cell === 1,
            'food': cell === 2,
            'snake-head': isSnakeHead(x, y)
          }"
        ></div>
      </div>
    </div>
    <div class="game-info">
      <p>得分: {{ score }}</p>
      <p>最高分: {{ highScore }}</p>
      <button @click="resetGame">重新开始</button>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted } from 'vue';

export default {
  setup() {
    // 游戏配置
    const gridSize = 20;
    const cellSize = 20;
    const gameSpeed = 150; // 毫秒

    // 游戏状态
    const grid = ref(createEmptyGrid());
    const snake = ref([{x: 10, y: 10}]);
    const direction = ref({x: 0, y: 0});
    const nextDirection = ref({x: 0, y: 0});
    const food = ref(null);
    const score = ref(0);
    const highScore = ref(0);
    const gameOver = ref(false);
    const gameBoard = ref(null);
    const gameInterval = ref(null);

    // 初始化空网格
    function createEmptyGrid() {
      return Array(gridSize).fill().map(()=> Array=(gridSize).fill(0));
    }

    // 更新网格显示
    function updateGrid() {
      const newGrid = createEmptyGrid();
      
      // 绘制蛇
      snake.value.forEach((segment =>{
        if(segment.x >= 0 && segment.x < gridSize && segment.y >= 0 && segment.y < gridSize){
          newGrid[segment.y][segment.x]=1;
        }
      }))
      // 绘制食物
      if (food.value) {
        newGrid[food.value.y][food.value.x] = 2;
      }
      
      grid.value = newGrid;
    }

    // 检查是否是蛇头
    function isSnakeHead(x, y) {

    }

    // 生成食物
    function generateFood() {
      const emptyCells = [];
      //食物要生成在范围内，不能生成在蛇身上
    }

    // 游戏主循环
    function gameLoop() {
      if (gameOver.value) return;
      
      // 更新方向
      direction.value = {...nextDirection.value};
      
      // 如果没有方向，不移动
      if (direction.value.x === 0 && direction.value.y === 0) {
        return;
      }
      
      // 计算新蛇头位置
      
      // 检查碰撞

      
      // 添加新蛇头

      
      // 检查是否吃到食物
      if () {
        score.value += 10;
        generateFood();
      } else {
        // 如果没有吃到食物，移除蛇尾

      }
      
      updateGrid();
    }

    // 键盘控制
    function handleKeyDown(e) {
      // 防止默认行为（如页面滚动）
      if ([37, 38, 39, 40].includes(e.keyCode)) {
        e.preventDefault();
      }
      
      //方向键按下，切换方向
    }

    // 重置游戏
    function resetGame() {
      snake.value = [{x: 10, y: 10}];
      direction.value = {x: 0, y: 0};
      nextDirection.value = {x: 0, y: 0};
      score.value = 0;
      gameOver.value = false;
      generateFood();
      updateGrid();
      
      // 确保游戏板获得焦点
      if (gameBoard.value) {
        gameBoard.value.focus();
      }
    }

    // 生命周期钩子
    onMounted(() => {
      generateFood();
      updateGrid();
      //设置定时器，周期性的执行回调函数
      
      // 确保游戏板获得焦点
      if (gameBoard.value) {
        gameBoard.value.focus();
      }
    });

    onUnmounted(() => {
      if (gameInterval.value) {
        clearInterval(gameInterval.value);
      }
    });

    return {
      grid,
      snake,
      score,
      highScore,
      gameBoard,
      isSnakeHead,
      handleKeyDown,
      resetGame
    };
  }
};
</script>

<style>
.game-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-family: Arial, sans-serif;
}

.game-board {
  display: flex;
  flex-direction: column;
  border: 2px solid #333;
  background-color: #f0f0f0;
  outline: none; /* 移除焦点时的轮廓 */
}

.row {
  display: flex;
}

.cell {
  width: 20px;
  height: 20px;
  box-sizing: border-box;
}

.snake {
  background-color: #4CAF50;
  border: 1px solid #45a049;
}

.snake-head {
  background-color: #2E7D32;
}

.food {
  background-color: #f44336;
  border-radius: 50%;
}

.game-info {
  margin-top: 20px;
  text-align: center;
}

button {
  padding: 8px 16px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

button:hover {
  background-color: #45a049;
}
</style>